package com.xsm.ppsecret.ui.log;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xsm.ppsecret.R;
import com.xsm.ppsecret.model.LogEntry;
import com.xsm.ppsecret.presenter.AddLogPresenter;
import com.xsm.ppsecret.ui.implview.IAddLogActivity;
import com.xsm.ppsecret.util.CryptUtil;
import com.xsm.ppsecret.util.JsonUtils;
import com.xsm.ppsecret.util.NativeHelper;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LogEditActivity extends AppCompatActivity implements IAddLogActivity {

    @BindView(R.id.menu_normal_title)
    TextView menuTitle;
    @BindView(R.id.menu_normal_action)
    TextView menuAction;
    @BindView(R.id.add_log_edit)
    EditText mEditText;
    private AddLogPresenter mAddLogPresenter = new AddLogPresenter(this);
    private LogEntry mLogEntry;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_log);
        ButterKnife.bind(this);
        menuTitle.setText("编辑日志");
        menuAction.setText("保存");
        String json = getIntent().getStringExtra("json");
        if (!TextUtils.isEmpty(json)) {
            mLogEntry = JsonUtils.getInstance().deserialize(json, LogEntry.class);
            if (mLogEntry != null) {
                String content = mLogEntry.getContent();
                if (!TextUtils.isEmpty(content)) {
                    mEditText.setText(content);
                    mEditText.setSelection(content.length());
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        super.onBackPressed();
        finish();
    }

    @OnClick(R.id.menu_normal_back)
    void back() {
        setResult(RESULT_OK);
        finish();
    }

    @OnClick(R.id.menu_normal_action)
    void save() {
        if (mLogEntry == null) {
            mAddLogPresenter.save(this, mEditText.getText().toString(), -1);
        } else {
            mAddLogPresenter.save(this, mEditText.getText().toString(), mLogEntry.getId());
        }
    }

    @Override
    public void saveOk() {
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void saveError(String errorMsg) {
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
    }


}
